package com.stu.day16;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zy
 * @date 2025/2/14 10:12
 */
public class ObjectDemo {
    public final static String PATH = "src/com/stu/day16/data/user.txt";

    public static void main(String[] args) {
        User user1 = new User(2,"jack");
        User user2 = new User(1,"tom");
        List<User> userList = new ArrayList<>();
        userList.add(user1);
        userList.add(user2);
        //writeObj(user1);
        writeList(userList);

        List<User> readUsers = readObj();
        System.out.println(readUsers);
    }

    /**
     * 对象的反序列化
     */
    public static List<User> readObj(){
        List<User> userList = new ArrayList<>();
        try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(PATH))){
            userList = (List<User>) in.readObject();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return userList;
    }

    public static void writeList(List<User> users){

        try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(PATH))) {
            //输出
            out.writeObject(users);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对象的序列化
     * @param user
     */
    public static void writeObj(User user){
        //构建操作对象类型的文件输出流
        //try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(PATH))) {

        //true是追加写入
        try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(PATH,true))) {
            //输出
            out.writeObject(user);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
class User implements Serializable {//否则java.io.NotSerializableException
    private Integer id;
    private String name;

    public User() {
    }

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("User{");
        sb.append("id=").append(id);
        sb.append(", name='").append(name).append('\'');
        sb.append('}');
        return sb.toString();
    }
}
